package IOStream_etc.BufferStream_etc;

import org.junit.Test;

import java.io.*;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/29 12:16
 * 说明：缓冲流，处理文本
 */

public class BufferedReaderWriterTest {
    // 使用BufferedReader将txt文件中的内容显示在控制台上
    @Test
    public void test1() throws IOException {
        File file = new File("AnyTXT.txt");

        // 处理流套节点流
        BufferedReader br = new BufferedReader(new FileReader(file));
        // 读取的过程

        /**
        // 方式1：read(char[] cBuffer)
        char[] cBuffer = new char[1024];
        int len;
        while ((len = br.read()) != -1){
            // 遍历方法1
//            for (int i = 0; i < len; i++) {
//                System.out.println(cBuffer[i]);
//            }
            // 遍历方法2
            String str = new String(cBuffer, 0, len);
            System.out.println(str);
        }

        br.close();
        */

        // 方式2：readLine() 按行读取，返回的字符串不包含换行符
        String data;
        while ((data = br.readLine()) != null){
            System.out.println(data + "\n");
        }
    }

    /**
     * 使用 BufferedReader和 BufferedWriter实现文本文件的复制
     */
    @Test
    public void test2() {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            File file1 = new File("AnyTXT.txt");
            File file2 = new File("AnyTXT_copy.txt");

            br = new BufferedReader(new FileReader(file1));
            bw = new BufferedWriter(new FileWriter(file2));

            String data;
            while ((data = br.readLine()) != null){
//                bw.write(data + "\n");
                // 或者
                bw.write(data);
                bw.newLine();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (bw != null) bw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if (br != null) br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }
}
